package my.suveng.util.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import my.suveng.model.common.interfaces.define.SpringUtil;
import my.suveng.model.common.response.expand.demo.ExpandDemo;
import my.suveng.util.json.Jackson;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@ControllerAdvice
@SpringUtil
public class SystemExceptionHandler {


    /**
     * 全局异常处理
     * @author suwenguang
     * @date 2019-09-25
     */
    @ExceptionHandler(value = Exception.class)
    public void defaultErrorHandler(Exception e, HttpServletResponse response) {
        // http 返回结果
        if (ObjectUtil.isEmpty(response)) {
            return;
        }
        // 如果已经返回,不处理
        if (response.isCommitted()) {
            return;
        }
        //解决乱码, 需要在writer前设置
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType("application/json;charset=UTF-8");
        // 获取http 的 writer
        PrintWriter writer;
        try {
            writer = response.getWriter();
        } catch (IOException ex) {
            return;
        }

        if (ObjectUtil.isEmpty(writer)) {
            return;
        }


        Throwable cause = e.getCause();
        String message = e.getMessage();
        if (ObjectUtil.isNotEmpty(cause)) {
            message = cause.getMessage();
        }

        writer.write(Jackson.toJsonString(ExpandDemo.build(HttpStatus.HTTP_INTERNAL_ERROR, message, new Object())));
        writer.flush();
        writer.close();
    }
}
